#include <iostream>
#include <queue>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right)
        : val(x), left(left), right(right) {}
};

vector<vector<int>> levelOrder(TreeNode* root) {
    if (root == nullptr) return vector<vector<int>>{};
    vector<vector<int>> ans;
    queue<TreeNode*> Q;
    Q.push(root);
    while (!Q.empty()) {
        int size = Q.size();
        vector<int> aa;
        for (int i = 0; i < size; i++) {
            if (Q.front()->left != nullptr) Q.push(Q.front()->left);
            if (Q.front()->right != nullptr) Q.push(Q.front()->right);
            aa.push_back(Q.front()->val);
            Q.pop();
        }
        ans.push_back(aa);
    }
    return ans;
}